/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package picasa;

import DAO.AlbumDAO;
import helper.TreeCellRender;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import model.*;

/**
 *
 * @author Tin Pham
 */
public class Main extends javax.swing.JFrame {

    ImageManager imageManager;
    BufferedImage[] images;
    private int imageIndex = 0;

    /**
     * Creates new form Main
     */
    public Main() {

        imageManager = new ImageManager();
        initComponents();
        this.createBufferStrategy(2);
        System.out.println(this.isDoubleBuffered());
        DefaultTreeModel model = (DefaultTreeModel) jTreeRoot.getModel();
        model.setRoot(new DefaultMutableTreeNode("Picasa"));
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();

        root.removeAllChildren();

        String path = "images";
        String files;
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();
        TreeCellRender render = new TreeCellRender();
        render.setRendererIcon(new ImageIcon("img/folder_icon.png"));
        jTreeRoot.setCellRenderer(render);


        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isDirectory()) {
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(listOfFiles[i].getName());
                node.setUserObject("images/" + listOfFiles[i].getName());
                root.add(node);
            }
        }

        model.reload();
        jTreeRoot.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                try {
                    doMouseClicked(me);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

    }

    void doMouseClicked(MouseEvent me) throws IOException {
        
        imageManager.removeAll();
        
        TreePath tp = jTreeRoot.getPathForLocation(me.getX(), me.getY());
        Object[] obj = tp.getPath();
        String pathNode = "";
        for (int i = 1; i < obj.length; i++) {
            Object path = ((DefaultMutableTreeNode) obj[i]).getUserObject();
            if (pathNode.length() > 0) {
                pathNode = pathNode + '/' + path;
            } else {
                pathNode = pathNode + path;
            }
        }
        String file;
        File folder = new File(pathNode);
        File[] listOfFiles = folder.listFiles();
        int padding = 10;

        int width = 200;
        int height = 200;
        for (int i = 0; i < listOfFiles.length; i++) {

            int numberColumn = 4;
            int indexColumn = i % numberColumn;
            int indexRow = i / 4;
            int x = indexColumn * (width + padding);
            int y = indexRow * (height + padding);

            if (listOfFiles[i].isFile()) {
                file = listOfFiles[i].getName();
                if (file.endsWith(".JPG") || file.endsWith(".PNG") || file.endsWith(".jpg") || file.endsWith(".png")) {
                    //System.out.println(pathNode + '/' + file);
                    String filePath = pathNode + '/' + file;
                    //imageManager.add(filePath, x, y, width, height);
                    //this.repaint();
                      
                    Image img = new Image(filePath, x, y, width, height);
                    imageManager.add(img);
                   

                    //break;
                }
            }

        }
        this.imageManager.setSize(jPanel2.getSize());
        
        this.jPanel2.add(this.imageManager);
        this.repaint();
        System.out.println("done");


    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        // imageManager.draw(jPanel2.getGraphics());
//        Graphics g2 = jPanel2.getGraphics();
//        BufferedImage img = new BufferedImage(jPanel2.getWidth(), jPanel2.getHeight(), BufferedImage.TYPE_INT_ARGB);
//        Graphics2D graphicsImage = img.createGraphics();
//        ((Graphics2D)g2).drawImage(img, null, 0, 0);
//        graphicsImage.dispose();
    }

    @Override
    public void paintComponents(Graphics g) {
        super.paintComponents(g);
    }

    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        menuBar1 = new java.awt.MenuBar();
        menu1 = new java.awt.Menu();
        menu2 = new java.awt.Menu();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTreeRoot = new javax.swing.JTree();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();

        menu1.setLabel("File");
        menuBar1.add(menu1);

        menu2.setLabel("Edit");
        menuBar1.add(menu2);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTreeRoot.setName("Picasa"); // NOI18N
        jScrollPane1.setViewportView(jTreeRoot);
        jTreeRoot.getAccessibleContext().setAccessibleName("");

        jPanel1.setName(""); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 897, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 695, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTree jTreeRoot;
    private java.awt.Menu menu1;
    private java.awt.Menu menu2;
    private java.awt.MenuBar menuBar1;
    // End of variables declaration//GEN-END:variables
}
